package org.xchris;

import android.app.Application;
import android.content.Context;

import org.xchris.http.ViseHttp;
import org.xchris.http.interceptor.HttpLogInterceptor;
import org.xchris.util.SSLUtil;
import org.xchris.view.ViewInjectorImpl;

import java.lang.reflect.Method;
import java.util.HashMap;

import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;

import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by wyouflf on 15/6/10.
 * 任务控制中心, http, image, db, view注入等接口的入口.
 * 需要在在application的onCreate中初始化: x.Ext.init(this);
 */
public final class x {

    private x() {
    }

    public static boolean isDebug() {
        return Ext.debug;
    }

    public static Application app() {
        if (Ext.app == null) {
            try {
                // 在IDE进行布局预览时使用
                Class<?> renderActionClass = Class.forName("com.android.layoutlib.bridge.impl.RenderAction");
                Method method = renderActionClass.getDeclaredMethod("getCurrentContext");
                Context context = (Context) method.invoke(null);
                Ext.app = new MockApplication(context);
            } catch (Throwable ignored) {
                throw new RuntimeException("please invoke x.Ext.init(app) on Application#onCreate()"
                        + " and register your Application in manifest.");
            }
        }
        return Ext.app;
    }

    public static ViewInjector view() {
        if (Ext.viewInjector == null) {
            ViewInjectorImpl.registerInstance();
        }
        return Ext.viewInjector;
    }

    public static class Ext {
        private static boolean debug;
        private static Application app;
        private static ViewInjector viewInjector;

        private Ext() {
        }
        public static void init(Application app) {
//            TaskControllerImpl.registerInstance();
            if (Ext.app == null) {
                Ext.app = app;
            }
            //引入http设置
            ViseHttp.init(app);
            ViseHttp.CONFIG()
                    //配置请求主机地址
                    .baseUrl("http://192.168.1.100/")
                    //配置全局请求头
                    .globalHeaders(new HashMap<String, String>())
                    //配置全局请求参数
                    .globalParams(new HashMap<String, String>())
                    //配置读取超时时间，单位秒
                    .readTimeout(30)
                    //配置写入超时时间，单位秒
                    .writeTimeout(30)
                    //配置连接超时时间，单位秒
                    .connectTimeout(30)
                    //配置请求失败重试次数
                    .retryCount(3)
                    //配置请求失败重试间隔时间，单位毫秒
                    .retryDelayMillis(1000)
                    //配置是否使用cookie
                    .setCookie(true)
                    //配置自定义cookie
//                .apiCookie(new ApiCookie(this))
                    //配置是否使用OkHttp的默认缓存
                    .setHttpCache(true)
                    //配置OkHttp缓存路径
//                .setHttpCacheDirectory(new File(ViseHttp.getContext().getCacheDir(), ViseConfig.CACHE_HTTP_DIR))
                    //配置自定义OkHttp缓存
//                .httpCache(new Cache(new File(ViseHttp.getContext().getCacheDir(), ViseConfig.CACHE_HTTP_DIR), ViseConfig.CACHE_MAX_SIZE))
                    //配置自定义离线缓存
//                .cacheOffline(new Cache(new File(ViseHttp.getContext().getCacheDir(), ViseConfig.CACHE_HTTP_DIR), ViseConfig.CACHE_MAX_SIZE))
                    //配置自定义在线缓存
//                .cacheOnline(new Cache(new File(ViseHttp.getContext().getCacheDir(), ViseConfig.CACHE_HTTP_DIR), ViseConfig.CACHE_MAX_SIZE))
                    //配置开启Gzip请求方式，需要服务器支持
//                .postGzipInterceptor()
                    //配置应用级拦截器
                    .interceptor(new HttpLogInterceptor()
                            .setLevel(HttpLogInterceptor.Level.BODY))
                    //配置网络拦截器
//                .networkInterceptor(new NoCacheInterceptor())
                    //配置转换工厂
                    .converterFactory(GsonConverterFactory.create())
                    //配置适配器工厂
                    .callAdapterFactory(RxJava2CallAdapterFactory.create())
                    //配置请求工厂
//                .callFactory(new Call.Factory() {
//                    @Override
//                    public Call newCall(Request request) {
//                        return null;
//                    }
//                })
                    //配置连接池
//                .connectionPool(new ConnectionPool())
                    //配置主机证书验证
                    .hostnameVerifier(new SSLUtil.UnSafeHostnameVerifier("http://192.168.1.100/"))
                    //配置SSL证书验证
                    .SSLSocketFactory(SSLUtil.getSslSocketFactory(null, null, null))
            //配置主机代理
//                .proxy(new Proxy(Proxy.Type.HTTP, new SocketAddress() {}))
            ;
        }



        public static void setDebug(boolean debug) {
            Ext.debug = debug;
        }

        public static void setViewInjector(ViewInjector viewInjector) {
            Ext.viewInjector = viewInjector;
        }

        public static void setDefaultHostnameVerifier(HostnameVerifier hostnameVerifier) {
            HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);
        }
    }

    private static class MockApplication extends Application {
        public MockApplication(Context baseContext) {
            this.attachBaseContext(baseContext);
        }
    }
}
